package com.suntine.familytree.test.goodluck;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.Arrays;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

/**
 * @corporation 
 * @author suntine
 * @creation 2011-4-23 下午07:57:26
 * @description 
 */
public class Eleven {

	
	static final int OPTION_NUM = 11;
	static final int WN_NUM = 5;
	static final String EVLEVN_DIR_PATH = "F:/eleven";
	static final String SPLIT_BY = " "; // 分隔符
	static final int LINE_LENGTH = 22; //行长度
	static final int WN_LENGTH = 14; //winning number 长度
	//static String stagePoint[] ={"0610:","1211:","1812:","2413:","3014:","3616:","4217:","4818:","5419:","6020:","6521:"};
	static String stagePoint[] ={"0610:","1211:","1812:","2413:","3014:","3616:","4217:","4818:","5419:","6020:","6521:"};
	
	static String fileName = "11-04-25.txt";
//	static int numArray[] = new int[OPTION_NUM+1];
	static Map<String,Number> numberMap;
	static boolean noUseStagepoint = true; //不进行阶段分析
	static boolean printMatrix = false; //打印矩阵
	class Number{
		
		public String number;
		public int removedTimes;
		public int targetTimes;
		
		public Number(String number){
			this.number = number;
			init();
		}
		
		public void init(){
			this.removedTimes = 0;
			this.targetTimes = 0;
		}
	}
	
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		String elevenFilePath = EVLEVN_DIR_PATH+"/"+fileName;
		System.out.println("********** begin **********");
		try {
			File elevenTXTFile = new File(elevenFilePath);
			
			if(!elevenTXTFile.getParentFile().exists())
				elevenTXTFile.getParentFile().mkdirs();
			
			if(!elevenTXTFile.exists()){
				elevenTXTFile.createNewFile();
			}
			
			StringBuffer sb = read_file_by_bufferedreader(elevenTXTFile);// read the winning number file
			
			//System.out.println("\ntxtcontent	length:("+sb.length()+")	:\n"+sb.toString());
			if(noUseStagepoint){
				stagePoint = new String[]{""};
			}
			
			for(int i=0;i<stagePoint.length;i++){
				String paraData ;
				if("".equals(stagePoint[i])){
					paraData = sb.toString();
				}else{
					int  stagePointBeginEndIndex = sb.indexOf(stagePoint[i]);
					int stagePointEndIndex = stagePointBeginEndIndex+LINE_LENGTH;
					if(stagePointBeginEndIndex>0 && stagePointEndIndex<=sb.length()){
						paraData = sb.substring(0,stagePointEndIndex);
					}else{
						continue;
					}
				}
				
				System.out.println("\n===============================BEGIN"+stagePoint[i]+"===========================================");
				numberMapInit();//初始化numberMap
				String wnMatrix[][] = two_dimensional_array_converter(paraData); // make a matrix 
//				array_init(numArray); // init the numArray
				// 被踢出几率分析
				removed_analyzer(wnMatrix);
				// 命中分析
				target_analyzer(wnMatrix);
				System.out.println("\n===============================END"+stagePoint[i]+"=============================================");
				
				
			}
			
			
			
			
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		
		System.out.println("\n\n********** end **********");
		
	}

	private static void numberMapInit(){
		numberMap = new HashMap<String,Number>();
		for(int i=1;i<=OPTION_NUM;i++){
			String number = i<10?"0"+i:""+i;
			numberMap.put(number, new Eleven().new Number(number));
		}
	}
	
	private static void target_analyzer(String[][] wnMatrix) {
		
		for(int i=0;i<wnMatrix.length;i++){
			for(int j=0;j<WN_NUM;j++){
				++(numberMap.get(wnMatrix[i][j]).targetTimes);
			}
		}
		
		Set set = numberMap.entrySet();
	    Map.Entry<String,Number>[] entries = (Map.Entry<String,Number>[]) set.toArray(new Map.Entry[set.size()]);
	    Arrays.sort(entries, new Comparator() {
	            public int compare(Object arg0, Object arg1) {
	                Long key1 = Long.valueOf(((Number)((Map.Entry) arg0).getValue()).targetTimes);
	                Long key2 = Long.valueOf(((Number)((Map.Entry) arg1).getValue()).targetTimes);
	                return key2.compareTo(key1);
	            }
        });
	    
	    System.out.println("\n\n命中分析结果：\n");
	    
	    for (Map.Entry<String,Number> e:entries) {
		      Number numberObj = e.getValue();
		      System.out.println("【"+numberObj.number+"】命中"+numberObj.targetTimes+"次");
	     }
		
	}

	private static void removed_analyzer(String[][] wnMatrix) {
		for(int i=0;i<wnMatrix.length-1;i++){
			
			String currentWn[] = wnMatrix[i];
			String nextWn[] = wnMatrix[i+1];
			
			for(int j=0;j<currentWn.length;j++){
				String wn = currentWn[j];
				boolean removedFlag = true; //剔除标记
				for(int k=0;k<nextWn.length;k++){
					if(wn.equals(nextWn[k])){
						removedFlag = false;
						break;
					}
				}
				if( removedFlag ){
//					int numberInt = Integer.parseInt(wn);
//					++numArray[numberInt];
					++(numberMap.get(wn).removedTimes);
					
				}
			}
			
		}
		
//		System.out.println("\n\n剔除分析结果：\n");
//		for(int l=1;l<numArray.length;l++){
//			System.out.println("数字"+(l<10?"0"+l:l)+"的剔除次数为："+numArray[l]+"次");
//		}
		System.out.println("\n\n剔除分析结果：\n");
		
		/*for (Iterator it = numberMap.entrySet().iterator(); it.hasNext();) {
		      Map.Entry<String,Number> e = (Map.Entry<String,Number>)it.next();
		      Number numberObj = e.getValue();
		      System.out.println("数字"+numberObj.number+"的剔除次数为："+numberObj.removedTimes+"次");
	     }*/
		
		Set set = numberMap.entrySet();
	    Map.Entry<String,Number>[] entries = (Map.Entry<String,Number>[]) set.toArray(new Map.Entry[set.size()]);
	    Arrays.sort(entries, new Comparator() {
	            public int compare(Object arg0, Object arg1) {
	                Long key1 = Long.valueOf(((Number)((Map.Entry) arg0).getValue()).removedTimes);
	                Long key2 = Long.valueOf(((Number)((Map.Entry) arg1).getValue()).removedTimes);
	                return key2.compareTo(key1);
	            }
        });
	    for (Map.Entry<String,Number> e:entries) {
		      Number numberObj = e.getValue();
		      System.out.println("【"+numberObj.number+"】剔除"+numberObj.removedTimes+"次");
	     }
	     
	}

	private static void array_init(int[] numArray) {
		for(int i=0;i<numArray.length;i++){
			numArray[i] = 0;
		}
	}

	private static String [][] two_dimensional_array_converter(String pataData) {
		
		final boolean needReverse = false;
		String data = pataData;
		data = data.replaceAll("\n","");
		data = data.replaceAll("\r","	");
//		data += "	";
		//System.out.println("\ndata	length:("+data.length()+")\n"+data);
		
		int wnBeginIndex = 7;
		int wnEndIndex = wnBeginIndex+WN_LENGTH;
		
		int rows = data.length()/LINE_LENGTH;
		String dataArray[][] = new String[rows][WN_NUM];//winning number two dimensional array;
		for(int i=0;i<rows;i++){
			
			if(data.length() > wnEndIndex){
				String wnStr = data.substring(wnBeginIndex, wnEndIndex);
				String wnArray[] = wnStr.split(SPLIT_BY);
				dataArray[i]=wnArray;
			}
			
			wnBeginIndex += LINE_LENGTH;
			wnEndIndex = wnBeginIndex+WN_LENGTH;
			
		}
		
		if(needReverse){
			
			for(int m=0;m<rows/2;m++){
				
				int n = rows-m-1;
				String temp[] = dataArray[m];
				dataArray[m] = dataArray[n];
				dataArray[n] = temp;
				
			}
			
		}
		if(printMatrix){
			
			System.out.print("\nnow this is the matrix :");
			for(int j=0;j<rows;j++ ){
				System.out.print("\n");
				for(int k=0;k<WN_NUM;k++){
					System.out.print(dataArray[j][k]+"	");
				}
			}
			
		}
		
		return dataArray;
		
		
	}

	private static StringBuffer read_file_by_bufferedreader(File elevenTXTFile)
			throws FileNotFoundException, IOException {
		FileReader fr = new FileReader(elevenTXTFile);
		BufferedReader br = new BufferedReader(fr);
		StringBuffer sb = new StringBuffer(); 
		/*char block[] = new char[300]; 
		while(fr.read(block)!=-1){
			sb.append(block); 
		}*/ 
//		    int num = 0;
		int in ;
		do{
			in = br.read();
			if(in != -1){
				char c = (char)in;
				sb.append(c);
//		    		num++;
			}
		}while(in != -1);
		br.close();
		fr.close();
		return sb;
	}

}
